package com.rainbowBoot.config.permission;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author 小熊
 * @version 1.0
 * @remark 权限拦截器配置
 */
@Configuration
public class PermissionConfig implements HandlerInterceptor {

    Logger logger = LogManager.getLogger(PermissionConfig.class);

    /**
     * 匹配权限
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.info("正在匹配权限...");
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // 得到拦截的方法
        Method method = handlerMethod.getMethod();
        // 获取方法的注解
        Permission permission = method.getAnnotation(Permission.class);
        // 没有注解则放行
        if(permission != null) {
            logger.info("没有权限限制，放行");
            return true;
        } else {
            // 拦截方法所有权限
            //String[] per = permission.value();
            // 用户自身权限
            //String userPer = (String)request.getSession().getAttribute("permission");
            //logger.info("用户权限：" + userPer);
            // 匹配

            try {
                request.getRequestDispatcher("/do/login/login").forward(request, response);
               // response.sendRedirect("../../do/login/login");
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
        // 拒绝请求
        return false;
    }

}
